package com.kky.pp.util

import android.R
import android.app.Activity
import android.graphics.Rect
import android.view.View
import android.view.ViewTreeObserver
import android.view.WindowManager
import android.widget.FrameLayout
import io.rong.imkit.utils.StatusBarUtil

class KeyboardUtils {
    var sDecorViewInvisibleHeightPre = 0
    private var onGlobalLayoutListener: ViewTreeObserver.OnGlobalLayoutListener? = null
    private var mNavHeight = 0

    private var sDecorViewDelta = 0

    private fun getDecorViewInvisibleHeight(activity: Activity): Int {
        val decorView = activity.window.decorView
            ?: return sDecorViewInvisibleHeightPre
        val outRect = Rect()
        decorView.getWindowVisibleDisplayFrame(outRect)
        val delta = Math.abs(decorView.bottom - outRect.bottom)
        if (delta <= mNavHeight) {
            sDecorViewDelta = delta
            return 0
        }
        return delta - sDecorViewDelta
    }

    /**
     * @param activity
     * @param view
     * @param listener
     */
    fun registerKeyboardHeightListener(
        activity: Activity,
        view: View? = null,
        listener: KeyboardHeightListener? = null
    ) {
        val flags = activity.window.attributes.flags
        if (flags and WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS != 0) {
            activity.window.clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
        }
        val contentView = activity.findViewById<FrameLayout>(R.id.content)
        sDecorViewInvisibleHeightPre = getDecorViewInvisibleHeight(activity)
        onGlobalLayoutListener = ViewTreeObserver.OnGlobalLayoutListener {
            //google手机 activity启动软键盘弹出 测算软键盘高度会有误差，延迟弹出软键盘可规避该问题
            val height = getDecorViewInvisibleHeight(activity)
            if (sDecorViewInvisibleHeightPre != height) {
                listener?.onKeyboardHeightChanged(height)
                sDecorViewInvisibleHeightPre = height
            }
           val translationY = if (height != 0) {
                -height * 1f
            } else {
                0f
            }
            view?.animate()?.translationY(translationY)?.setDuration(150)?.start()
        }
        //获取到导航栏高度之后再添加布局监听
        mNavHeight = StatusBarUtil.getStatusBarHeight(activity) + DensityUtil.dip2px(activity, 44f)
        contentView.viewTreeObserver.addOnGlobalLayoutListener(onGlobalLayoutListener)
    }

    fun unregisterKeyboardHeightListener(activity: Activity) {
        onGlobalLayoutListener = null
        val contentView = activity.window.decorView.findViewById<View>(R.id.content)
            ?: return
        contentView.viewTreeObserver.removeGlobalOnLayoutListener(onGlobalLayoutListener)
    }


    interface KeyboardHeightListener {
        fun onKeyboardHeightChanged(height: Int)
    }
}